package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.entity.Meeting;
import com.example.cemenghuii.entity.MeetingRegistration;
import com.example.cemenghuii.entity.User;
import com.example.cemenghuii.service.MeetingService;
import com.example.cemenghuii.service.UserService;
import com.example.cemenghuii.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/meeting")
@CrossOrigin(origins = "*")
public class MeetingController {

    @Autowired
    private MeetingService meetingService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建会议
     */
    @PostMapping
    public ApiResponse<Void> createMeeting(@RequestHeader("Authorization") String token,
                                           @RequestBody Meeting meeting) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            User user = userService.getUserById(userId);
            if (user == null) {
                return ApiResponse.unauthorized("用户不存在");
            }

            meeting.setCreatorId(userId);
            meeting.setCreatorName(user.getUsername());

            boolean success = meetingService.createMeeting(meeting);
            if (success) {
                if (userType == 2) {
                    return ApiResponse.success("会议创建成功");
                } else {
                    return ApiResponse.success("会议提交成功，等待审核");
                }
            } else {
                return ApiResponse.error("会议创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新会议
     */
    @PutMapping("/{id}")
    public ApiResponse<Void> updateMeeting(@RequestHeader("Authorization") String token,
                                           @PathVariable Long id,
                                           @RequestBody Meeting meeting) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!meetingService.checkMeetingPermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此会议");
            }

            meeting.setId(id);
            // 企业用户修改后需要重新审核
            if (userType == 1) {
                meeting.setStatus(0); // 重新设为待审核
            }

            boolean success = meetingService.updateMeeting(meeting);
            if (success) {
                return ApiResponse.success("会议更新成功");
            } else {
                return ApiResponse.error("会议更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除会议
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteMeeting(@RequestHeader("Authorization") String token,
                                           @PathVariable Long id) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!meetingService.checkMeetingPermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此会议");
            }

            boolean success = meetingService.deleteMeeting(id);
            if (success) {
                return ApiResponse.success("会议删除成功");
            } else {
                return ApiResponse.error("会议删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取会议详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Meeting> getMeetingDetail(@PathVariable Long id) {
        try {
            Meeting meeting = meetingService.getMeetingById(id);
            if (meeting == null) {
                return ApiResponse.notFound("会议不存在");
            }
            return ApiResponse.success(meeting);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取会议列表
     */
    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> getMeetingList(@RequestHeader("Authorization") String token,
                                                           @RequestParam(required = false) String meetingName,
                                                           @RequestParam(required = false) String meetingType,
                                                           @RequestParam(required = false) String creatorName,
                                                           @RequestParam(required = false) Integer status,
                                                           @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
                                                           @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
                                                           @RequestParam(defaultValue = "1") Integer page,
                                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            Long creatorId = null;
            // 企业用户只能查看自己的会议
            if (userType == 1) {
                creatorId = userId;
            }

            Map<String, Object> result = meetingService.getMeetingList(meetingName, meetingType, creatorName,
                    status, creatorId, startDate, endDate, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取我的会议列表
     */
    @GetMapping("/my")
    public ApiResponse<Map<String, Object>> getMyMeetingList(@RequestHeader("Authorization") String token,
                                                             @RequestParam(defaultValue = "1") Integer page,
                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            Map<String, Object> result = meetingService.getMeetingByCreatorId(userId, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 审核会议（管理员功能）
     */
    @PutMapping("/{id}/audit")
    public ApiResponse<Void> auditMeeting(@RequestHeader("Authorization") String token,
                                          @PathVariable Long id,
                                          @RequestBody Map<String, Integer> auditData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Integer status = auditData.get("status");
            boolean success = meetingService.auditMeeting(id, status);
            if (success) {
                String message = status == 1 ? "审核通过" : "审核拒绝";
                return ApiResponse.success(message);
            } else {
                return ApiResponse.error("审核失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取待审核会议列表（管理员功能）
     */
    @GetMapping("/pending")
    public ApiResponse<Map<String, Object>> getPendingMeetingList(@RequestHeader("Authorization") String token,
                                                                  @RequestParam(defaultValue = "1") Integer page,
                                                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Map<String, Object> result = meetingService.getPendingMeetingList(page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取已发布会议列表（小程序端）
     */
    @GetMapping("/published")
    public ApiResponse<Map<String, Object>> getPublishedMeetingList(@RequestParam(required = false) String keyword,
                                                                    @RequestParam(required = false) String meetingType,
                                                                    @RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = meetingService.getPublishedMeetingList(keyword, meetingType, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据会议类型获取会议列表
     */
    @GetMapping("/type/{meetingType}")
    public ApiResponse<Map<String, Object>> getMeetingByType(@PathVariable String meetingType,
                                                             @RequestParam(defaultValue = "1") Integer page,
                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = meetingService.getMeetingByType(meetingType, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取即将开始的会议
     */
    @GetMapping("/upcoming")
    public ApiResponse<Map<String, Object>> getUpcomingMeetings(@RequestParam(defaultValue = "1") Integer page,
                                                                @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = meetingService.getUpcomingMeetings(page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 会议报名（小程序端）
     */
    @PostMapping("/{id}/register")
    public ApiResponse<Void> registerMeeting(@PathVariable Long id,
                                             @RequestBody MeetingRegistration registration) {
        try {
            registration.setMeetingId(id);
            boolean success = meetingService.registerMeeting(registration);
            if (success) {
                return ApiResponse.success("报名成功");
            } else {
                return ApiResponse.error("报名失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 取消报名（小程序端）
     */
    @DeleteMapping("/{id}/register")
    public ApiResponse<Void> cancelRegistration(@PathVariable Long id,
                                                @RequestParam String openId) {
        try {
            boolean success = meetingService.cancelRegistration(id, openId);
            if (success) {
                return ApiResponse.success("取消报名成功");
            } else {
                return ApiResponse.error("取消报名失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取会议报名列表
     */
    @GetMapping("/{id}/registrations")
    public ApiResponse<Map<String, Object>> getMeetingRegistrations(@RequestHeader("Authorization") String token,
                                                                    @PathVariable Long id,
                                                                    @RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限：超级管理员或会议创建者可以查看报名列表
            if (!userService.isSuperAdmin(userId) && !meetingService.checkMeetingPermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限查看此会议的报名信息");
            }

            Map<String, Object> result = meetingService.getMeetingRegistrations(id, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 检查用户是否已报名会议（小程序端）
     */
    @GetMapping("/{id}/check-registration")
    public ApiResponse<Map<String, Object>> checkUserRegistration(@PathVariable Long id,
                                                                  @RequestParam String openId) {
        try {
            boolean registered = meetingService.checkUserRegistration(id, openId);
            Map<String, Object> result = Map.of("registered", registered);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}